package com.ctfo.ulcp.exp.db

import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll

data class Project(var id: Int?, val name: String, val code: String, val summary: String, val description: String?)

object Projects : Table("t_project") {
    private val id = integer("ID").autoIncrement()
    private val name = varchar("NAME", length = 255)
    private val summary = text("SUMMARY")
    private val description = varchar("DESCRIPTION", length = 255).nullable()
    private val code = varchar("CODE", length = 255).uniqueIndex()

    override val primaryKey = PrimaryKey(id)

    fun create(project: Project): Project {
        project.id = Projects.insert {
            it[name] = project.name
            it[code] = project.code
            it[summary] = project.summary
            it[description] = project.description
        }[id]
        return project
    }

    fun findByCode(code: String): Project? {
        return Projects.selectAll().where { Projects.code eq code }.limit(1)
            .map {
                Project(
                    it[id],
                    it[name],
                    it[Projects.code],
                    it[summary],
                    it[description]
                )
            }
            .singleOrNull()
    }

}